package com.example.common.utils.thread_pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author zwp14
 * @create 2024/6/21 16:16
 * @description java核心包自带的线程池
 */
public class ExecutorUtil {

    /**
     * @param coreSize 核心线程数
     * @param maxSize 最大线程数 = 核心线程数+临时线程数
     * @param aliveTime 临时线程存活时间
     * @param workQueueSize 线程队列数量 ，当线程队列数量满了将创建临时线程
     * @return 线程池
     * @description 根据所需，自己设置线程池的参数
     */
    public static ThreadPoolExecutor getExecutor(Integer coreSize,Integer maxSize,
                                                 Integer aliveTime,Integer workQueueSize){
        return new ThreadPoolExecutor(
                coreSize,
                maxSize,
                aliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(workQueueSize),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    /**
     * @return 创建默认的线程池
     */
    public static ThreadPoolExecutor defaultExecutor(){
        return new ThreadPoolExecutor(
                5,
                10,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
